<template>
	<view class="">
		<toolTabs :list='["按企业统计","按地区统计"]' @change='tabsChange' />
		<view class="sub">
			<u-subsection :list=subList :current="curNow" @change="sectionChange" bgColor='#FFFFFF'
				activeColor='#1D62BE' fontSize='14px' style='margin: 10px 0'></u-subsection>
		</view>
		<view class="search" v-if='isSearch'>
			<u--form :model="formData" ref="uForm">
				<u-form-item label="行政区划" prop="areaName" labelWidth='80px' @click='openPicker'>
					<u-input v-model="areaName" placeholder="请输入行政区划">
					</u-input>
				</u-form-item>
				<u-form-item label="企业名称" prop="archiveName" labelWidth='80px' v-if="tabInde==0">
					<u-input v-model="formData.archiveName" placeholder="请输入企业名称" @blur="handleVeh" style='width: 90%;'>
					</u-input>
				</u-form-item>
				<u-form-item label="评估时间" prop="evalSection" labelWidth='80px'>
					<uni-datetime-picker type="daterange" v-model="formData.evalSection" :clear-icon='false' />
				</u-form-item>
			</u--form>

			<view class="but">
				<u-button type="primary" text="查询" class='u_but' @click="search('sort','scroll','isClick')"></u-button>
				<u-button type="info" text="重置" class='u_but' @click="reset()"></u-button>
			</view>
			<view class="cancel" @click="isSearch=false">
				<img src="/static/img/cencel.png" style='width:30px;height: 30px;' alt="">
			</view>
		</view>

		<!-- 企业统计 -->
		<similarChart v-if="isChartOwner" :isSort="true" type="owner" :list='ownerList' @change='changeChartOwner'
			ref="simiChart" chartText='日均合规率' :curNow='curNow' />

		<!-- 地区统计 -->
		<similar-chart v-if="isChartArea" :isSort="true" type="area" :list='areaList' @change='changeChartArea'
			chartText='各地区日均合规率' ref="simiArea" :curNow='curNow' />


		<!--企业统计  -->
		<view class="tableCss" v-if="tabInde==0">
			<scroll-view scroll-y="true" @scrolltolower="scrolltolower" class="scroll-view">
				<v-table :columns="curNow==0?columnsOwner:columnsTime" :list="dataList" thColor='#D7E7FC'
					typeQuote='examine' @change='sortChange'>
				</v-table>
			</scroll-view>
		</view>

		<!--地区统计  -->
		<view class="tableCss" v-if="tabInde==1">
			<v-table :columns="curNow==0?columnsArea:columnsAreaTime" :list="dataAreaList" thColor='#D7E7FC'
				typeQuote='examine' @change='sortChangeArea'></v-table>
		</view>

		<selectTask ref="selectTaskRef" @change="changeVeh" />

		<lotus-address v-on:choseVal="choseValue" :lotusAddressData="lotusAddressData"></lotus-address>
	</view>
</template>

<script>
	import selectTask from '@/components/tool-select/select-task.vue'
	import vTable from '../components/table-list.vue'
	import toolTabs from "@/components/tool-tabs/stat-tabs.vue"
	import similarChart from "@/components/similar-chart/index.vue"
	import {
		queryOwnerName
	} from '@/common/api/monitor.js'
	import * as api from '@/common/api/riskAssess.js'
	import {
		dateTransition
	} from '@/common/util.js'
	export default {
		components: {
			vTable,
			toolTabs,
			similarChart,
			selectTask,
		},
		data() {
			return {
				columnsOwner: [{
						title: "名称",
						key: 'archiveName',
						$width: '90px',
					},
					{
						title: '区划',
						key: 'areaName',
						$width: '3em',
					},
					{
						title: '动力车',
						key: 'powerSum',
					},
					{
						title: '处罚数',
						key: 'moleculeSize',
						format: ({
							item
						}) => {
							return `<span style="color:#297EFD;">${item.moleculeSize}</span>`;
						},
						handle: (
							item
						) => {
							this.$goBack('/pages/dgs_hg/monitorAna/components/details?type=jtzfcfajl&rowData=' +
								encodeURIComponent(JSON
									.stringify(item)), 2);
						},
					},
					{
						title: '日均率',
						key: 'averageItemScore',
						format: ({
							item
						}) => {
							return `<span style="color:#297EFD;">${item.averageItemScore}</span>`;
						},
						handle: (
							item
						) => {
							this.curNow = 1
							this.formData.archiveName = item.archiveName
							this.tablePages.current = 1
							this.dataList = []
							this.searchTime('scroll', 'isClick')
						},
					},
					{
						title: '排名',
						key: 'indexC',
						$width: '3em',
					}

				],
				columnsTime: [{
						title: "统计时间",
						key: 'evalSection',
						$width: '50px',
					},
					{
						title: '名称',
						key: 'archiveName',
						$width: '80px',
					},
					{
						title: '区划',
						key: 'areaName',
						$width: '60px',
					},
					{
						title: '动力车',
						key: '',
						format: ({
							item
						}) => {
							return `<span>${item.simArchiveDetailVOList[0]?.powerSum }</span>`;
						},
					},
					{
						title: '处罚数',
						key: '',
						format: ({
							item
						}) => {
							return `<span>${item.simArchiveDetailVOList[0]?.carSize }</span>`;
						},
					},
					{
						title: '合规率',
						key: 'simArchiveDetailVOList[0].itemScore ',
						format: ({
							item
						}) => {
							return `<span style="color:#297EFD;">${item.simArchiveDetailVOList[0]?.itemScore }</span>`;
						},
						handle: (
							item
						) => {
							this.$goBack('/pages/dgs_hg/monitorAna/components/details?type=jtzfcfajl&rowData=' +
								encodeURIComponent(JSON
									.stringify(item)), 2);
						},

					},

				],
				dataList: [],
				ownerList: [],

				columnsArea: [{
						title: '区划',
						key: 'areaName',
						$width: '100px',
					},
					{
						title: '动力车',
						key: 'powerSum',
					},
					{
						title: '处罚数',
						key: 'moleculeSize',
						format: ({
							item
						}) => {
							return `<span style="color:#297EFD;">${item.moleculeSize}</span>`;
						},
						handle: (
							item
						) => {
							this.$goBack('/pages/dgs_hg/monitorAna/components/details?type=jtzfcfajl&rowData=' +
								encodeURIComponent(JSON
									.stringify(item)), 2);
						},
					},
					{
						title: '日均率',
						key: 'averageItemScore',
						format: ({
							item
						}) => {
							return `<span style="color:#297EFD;">${item.averageItemScore}</span>`;
						},
						handle: (
							item
						) => {
							this.curNow = 1
							this.formData.areaCode = item.areaCode
							this.areaName = item.areaName
							this.dataAreaList = []
							this.searchAreaTime()
						},
					},
					{
						title: '排名',
						key: 'indexC',
						$width: '2em',
					}
				],
				columnsAreaTime: [{
						title: "统计时间",
						key: 'evalSection',
						$width: '50px',
					},
					{
						title: '区划',
						key: 'areaName',
						$width: '60px',
					},
					{
						title: '动力车',
						key: 'powerSum',
					},
					{
						title: '处罚数',
						key: '',
						format: ({
							item
						}) => {
							return `<span>${item.simArchiveDetailVOList[0]?.carSize }</span>`;
						},

					},
					{
						title: '处罚率',
						key: 'simArchiveDetailVOList[0].itemScore ',
						format: ({
							item
						}) => {
							return `<span style="color:#297EFD;">${item.simArchiveDetailVOList[0]?.itemScore }</span>`;
						},
						handle: (
							item
						) => {
							this.$goBack('/pages/dgs_hg/monitorAna/components/details?type=jtzfcfajl&rowData=' +
								encodeURIComponent(JSON
									.stringify(item)), 2);
						},

					},

				],
				dataAreaList: [],
				areaList: [],

				curNow: 0,
				formData: {
					areaCode: "",
					archiveName: "",
					evalSection: []
				},
				areaName: "",
				tabInde: 0,
				isSearch: false,
				tablePages: {
					current: 1,
					total: 0,
					size: 10
				},
				val: "",
				subList: ['按企业', '按时间'],
				orderData: "desc", //desc asc
				isChartOwner: false,
				isChartArea: false,
				// provinceShow: false, //行政区划
				lotusAddressData: {
					visible: false,
					provinceName: '',
					cityName: '',
					townName: '',
				},
			};
		},

		// onLoad(option) {

		// },
		// 右上角搜索
		onNavigationBarButtonTap(event) {
			this.isSearch = true
			// console.log('nav button pressed', event)
		},

		mounted() {
			this.searchOwner('sort', 'scroll')
		},

		methods: {

			openPicker() {
				this.lotusAddressData.visible = true;
				// 默认选择
				// this.lotusAddressData.provinceName = '湖北省';
				// this.lotusAddressData.cityName = '合肥市';
				// this.lotusAddressData.townName = '瑶海区';
			},

			//回传已选的省市区的值
			choseValue(res) {
				//res数据源包括已选省市区与省市区code
				console.log(res);
				this.lotusAddressData.visible = res.visible; //visible为显示与关闭组件标识true显示false隐藏
				//res.isChose = 1省市区已选 res.isChose = 0;未选
				if (res.isChose) {
					this.lotusAddressData.provinceName = res.province; //省
					this.lotusAddressData.cityName = res.city; //市
					this.lotusAddressData.townName = res.town; //区
					this.areaName = `${res.province} ${res.city} ${res.town}`; //region为已选的省市区的值
					// console.log(3123123,this.formData)
					if (res.town) {
						this.formData.areaCode = res.townCode
						return
					}

					if (res.city) {
						this.formData.areaCode = res.cityCode
						return
					}

					if (res.province) {
						this.formData.areaCode = res.provinceCode
						return
					}

				}
			},

			// 查询 //sort 图表是否排序 scroll表格是否下拉刷新 isClick 查询是否返回第一页
			search(sort, scroll, isClick) {
				if (this.tabInde == 0) {
					if (isClick) {
						this.tablePages.current = 1
					}
					if (this.curNow == 0) {
						this.searchOwner(sort, scroll, isClick)
					} else {
						this.searchTime(scroll, isClick)
					}

				} else {
					if (this.curNow == 0) {
						this.searchArea()
					} else {
						this.searchAreaTime()
					}

				}
				this.isSearch = false
			},

			scrolltolower(e) {
				if (this.tabInde == 0) {
					this.tablePages.current += 1
					this.search('', 'scroll')
				}
			},

			sortChange(order) {
				this.orderData = order
				this.searchOwner('', 'scroll', 'isClick')
			},

			// 地区-地区表格排序
			sortChangeArea() {
				this.dataAreaList.reverse()
			},



			getTime() {
				if (this.formData.evalSection == [] || this.formData.evalSection == null || this.formData.evalSection
					.length == 0) {
					api.queryLatelyEvalSection().then((res) => {
						this.formData.evalSection = res.data.data || res.data.data.data
						this.val = this.getTwoMiddle(
							this.formData.evalSection[0],
							this.formData.evalSection[1])
					});
				} else {
					this.val = this.getTwoMiddle(
						this.formData.evalSection[0],
						this.formData.evalSection[1])
				}
			},

			//企业- 企业查询
			searchOwner(isSort, isScroll, isClick) {
				// if (isSort) this.isChartOwner = true
				this.ownerList = []
				this.getTime()
				setTimeout(() => {
					const searchData = {
						...this.tablePages,
						...this.formData,
						itemCode: "jtzfcfajl",
						evalSection: this.val,
						orderFlag: '1',
						order: this.orderData
					};
					api.simSingleResultns(searchData).then(res => {
						// 下啦刷新
						if (isScroll) {
							if (res.data.data.records.length == 0) {
								this.dataList = []
							} else if (isClick) {
								this.dataList = res.data.data.records
							} else {
								this.dataList.push(...res.data.data.records)
							}
						}

						// 图表排序
						if (isSort) {
							if (res.data.data.records.length < 7) {
								for (let i = 0; i < res.data.data.records.length; i++) {
									this.ownerList.push({
										value: res.data.data.records[i].averageItemScore,
										name: res.data.data.records[i].archiveName
									})
								}

							} else {
								for (let i = 0; i < 8; i++) {
									this.ownerList.push({
										value: res.data.data.records[i].averageItemScore,
										name: res.data.data.records[i].archiveName
									})
								}
							}

							this.isChartOwner = true
							if (this.$refs.simiChart) {
								this.$refs.simiChart.init()
							}
						}

					})
				}, 200);
			},

			// 企业-时间查询
			searchTime(isScroll, isClick) {
				// this.ownerList = []
				this.getTime()
				const searchData = {
					...this.formData,
					...this.tablePages,
					itemCode: "jtzfcfajl",
					evalSection: this.val

				};
				api.simSingleResultnstime(searchData).then(res => {
					if (isScroll) {
						if (res.data.data.records.length == 0) {
							this.dataList = []
						} else if (isClick) {
							this.dataList = res.data.data.records
						} else {
							this.dataList.push(...res.data.data.records)
						}
					}

				})
			},

			// 企业图表排序
			changeChartOwner(item) {
				this.orderData = item
				this.tablePages.current = 1
				this.searchOwner('sortData')
			},

			// 地区-地区查询
			searchArea() {
				this.areaList = []
				this.getTime()
				const data = {
					...this.formData,
					// ...this.tableAreaPages,
					itemCode: "jtzfcfajl",
					evalSection: this.val,
				}
				api.simSingleResultsf(data).then(res => {
					this.dataAreaList = res.data.data
					res.data.data.map(item => {
						this.areaList.push({
							value: item.averageItemScore,
							name: item.areaName
						})
					})

					this.isChartArea = true
				})
			},

			// 地区-时间查询
			searchAreaTime() {
				this.getTime()
				const searchData = {
					...this.formData,
					itemCode: "jtzfcfajl",
					evalSection: this.val
				};

				api.simSingleResultsftime(searchData).then(rst => {
					this.dataAreaList = rst.data.data
					// rst.data.data.map(item => {
					// 	this.areaList.push({
					// 		value: item.simArchiveDetailVOList[0].itemScore,
					// 		name: item.areaName
					// 	})
					// })
					// this.$refs.simiArea.init()
				})
			},

			// 地区-图表排序
			changeChartArea() {
				this.$refs.simiArea.init()
			},

			// 企业 / 地区 切换
			tabsChange(item) {
				this.tabInde = item

				if (item == 0) {
					this.isChartArea = false
					this.curNow = 0
					this.searchOwner('sortAsc')
					this.subList = ['按企业', '按时间']
				}

				if (item == 1) {
					this.curNow = 0
					this.isChartOwner = false
					this.searchArea()
					this.subList = ['按地区', '按时间']
				}
			},

			// 企业/时间 切换
			sectionChange(index) {
				this.curNow = index;
				this.areaName = ''
				this.formData.archiveName = ''
				this.formData.areaCode = ''
				if (this.tabInde == 0) {
					this.dataList = []
					if (index == 0) {
						this.searchOwner('sort', 'scroll')
					}
					if (index == 1) {
						this.searchTime('scroll')
					}
				} else {
					this.dataAreaList = []
					if (index == 0) {
						this.searchArea()
					}
					if (index == 1) {
						this.searchAreaTime()
					}
				}

			},

			// 企业查询
			handleVeh() {
				this.$refs.selectTaskRef.showBox({
					title: "请选择企业名称",
					data: 0,
					key: this.formData.archiveName,
					getData: (key) => {
						return new Promise((resolve) => {
							queryOwnerName({
								ownerName: key
							}).then((res) => {
								resolve(res.data.data);
							}).catch(res => {});
						})
					}
				});
			},

			// 企业查询change
			changeVeh(res) {
				const item = res.item
				this.formData.archiveName = item.ownerName;
			},

			// 行政区划
			// provinceConfirm(e) {
			// 	this.areaName = e.value[0].name
			// 	this.formData.areaCode = e.value[0].id
			// 	this.provinceShow = false
			// },

			reset() {
				// this.$refs.uForm.resetFields()
				this.areaName = ''
				this.formData.archiveName = ''
				this.formData.areaCode = ''

			},

			// 时间格式化
			getTwoMiddle(date1, date2) {
				const times = new Date(date2) - new Date(date1) + 1;
				const days = times / 86400000;
				const res = [];
				const newDate = new Date(date1);
				res.push(dateTransition(newDate, "yyyy年M月d日"));
				for (let i = 1; i < days; i++) {
					newDate.setDate(newDate.getDate() + 1);
					res.push(dateTransition(newDate, "yyyy年M月d日"));
				}
				return res.toString();
			},
		}
	}
</script>

<style lang="scss">
	page {
		width: 100%;
		height: 100%;
		background: #F2F2F2;
	}

	.sub {
		padding: 0 10px;
	}

	.tableCss {
		// padding: 0 10px;
		// height: 50vh;
		background-color: #fff;
		margin: 0 10px;

	}

	.scroll-view {
		height: 50vh;
	}

	.search {
		background: #fff;
		margin: 0 10px 10px 10px;
		border-radius: 10px;
		padding: 15px;
		position: relative;

		.but {
			display: flex;
			justify-content: center;
			margin: 10px 0 0 0;

			.u_but {
				width: 40%;
			}
		}

		.cancel {
			width: 30px;
			position: absolute;
			right: -8px;
			top: -8px;
		}

	}

	::v-deep .u-subsection__bar,
	.u-subsection--button__bar {
		background: #EBF3FE;
	}

	::v-deep .text-center {
		font-size: 12px;
	}

	::v-deep .uni-date__x-input {
		padding: 0;
	}
</style>
